﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace N2.BlogEngine.Providers
{
	using BlogEngine;
	using Items;
	using N2;
	using be = global::BlogEngine.Core;
	using n2 = N2.BlogEngine;
	
	partial class N2BlogProvider
	{
		public override be.Page SelectPage(Guid id)
		{
			var _page = Context.Persister.Get<BePage>(id.ToInt());

			if (null == _page && this.UseFallBackProvider) {
				be.Page _innerPage = FallBackProvider.SelectPage(id);
				_innerPage.Id = id;
				this.UpdatePage(_innerPage);

				return _innerPage;
			}

			return _page.AsBlogEngine();
		}

		public override void InsertPage(be.Page page)
		{
			this.UpdatePage(page);
		}

		public override void UpdatePage(be.Page page)
		{
			Context.Persister.Save(page.AsN2());
		}

		public override void DeletePage(be.Page page)
		{
			Context.Persister.Delete(page.AsN2());
		}

		public List<be.Page> TryFillingPages()
		{
			return
				n2.BlogService
					.CurrentBlog
					.Pages
					.ItemHierarchy
					.Select<BePage, be.Page>(ItemExtensions.AsBlogEngine)
					.ToList();
		}

		public override List<be.Page> FillPages()
		{
			var _pages = this.TryFillingPages();

			if (!_pages.Any() && this.UseFallBackProvider) {
				FallBackProvider.FillPages();
				_pages = this.TryFillingPages();
			}

			return _pages;
		}
	}
}
